using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
namespace Microsoft.Expression.Interactivity.Input
{
	public class KeyTrigger : EventTriggerBase<UIElement>
	{
		public static readonly DependencyProperty KeyProperty = DependencyProperty.Register("Key", typeof(Key), typeof(KeyTrigger), null);
		public static readonly DependencyProperty ModifiersProperty = DependencyProperty.Register("Modifiers", typeof(ModifierKeys), typeof(KeyTrigger), null);
		public static readonly DependencyProperty FiredOnProperty = DependencyProperty.Register("FiredOn", typeof(KeyTriggerFiredOn), typeof(KeyTrigger), null);
		private UIElement targetElement;
		public Key Key
		{
			get
			{
				return (Key)base.GetValue(KeyTrigger.KeyProperty);
			}
			set
			{
				base.SetValue(KeyTrigger.KeyProperty, value);
			}
		}
		public ModifierKeys Modifiers
		{
			get
			{
				return (ModifierKeys)base.GetValue(KeyTrigger.ModifiersProperty);
			}
			set
			{
				base.SetValue(KeyTrigger.ModifiersProperty, value);
			}
		}
		public KeyTriggerFiredOn FiredOn
		{
			get
			{
				return (KeyTriggerFiredOn)base.GetValue(KeyTrigger.FiredOnProperty);
			}
			set
			{
				base.SetValue(KeyTrigger.FiredOnProperty, value);
			}
		}
		protected override string GetEventName()
		{
			return "Loaded";
		}
		private void OnKeyPress(object sender, KeyEventArgs e)
		{
			if (e.get_Key() == this.Key && Keyboard.get_Modifiers() == KeyTrigger.GetActualModifiers(e.get_Key(), this.Modifiers))
			{
				base.InvokeActions(e);
			}
		}
		private static ModifierKeys GetActualModifiers(Key key, ModifierKeys modifiers)
		{
			if (key == 5)
			{
				modifiers |= 2;
			}
			else
			{
				if (key == 6)
				{
					modifiers |= 1;
				}
				else
				{
					if (key == 4)
					{
						modifiers |= 4;
					}
				}
			}
			return modifiers;
		}
		protected override void OnEvent(EventArgs eventArgs)
		{
			this.targetElement = Application.get_Current().get_RootVisual();
			if (this.FiredOn == KeyTriggerFiredOn.KeyDown)
			{
				this.targetElement.add_KeyDown(new KeyEventHandler(this.OnKeyPress));
				return;
			}
			this.targetElement.add_KeyUp(new KeyEventHandler(this.OnKeyPress));
		}
		protected override void OnDetaching()
		{
			if (this.targetElement != null)
			{
				if (this.FiredOn == KeyTriggerFiredOn.KeyDown)
				{
					this.targetElement.remove_KeyDown(new KeyEventHandler(this.OnKeyPress));
				}
				else
				{
					this.targetElement.remove_KeyUp(new KeyEventHandler(this.OnKeyPress));
				}
			}
			base.OnDetaching();
		}
		private static UIElement GetRoot(DependencyObject current)
		{
			UIElement result = null;
			while (current != null)
			{
				result = (current as UIElement);
				current = VisualTreeHelper.GetParent(current);
			}
			return result;
		}
	}
}
